package cn.engage.system.service.impl;

import cn.engage.basic.query.BaseQuery;
import cn.engage.basic.service.impl.BaseServiceImpl;
import cn.engage.basic.util.PageList;
import cn.engage.system.domain.Menu;
import cn.engage.system.domain.Permission;
import cn.engage.system.domain.Role;
import cn.engage.system.mapper.MenuMapper;
import cn.engage.system.mapper.PermissionMapper;
import cn.engage.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-10-24
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public void add(Role role) {
        super.add(role);
        //添加菜单权限
        permissionMapper.addMiddle(role.getId(),role.getPermissions());
        // 添加 按钮权限
        menuMapper.addMiddle(role.getId(),role.getMenus());

    }

    @Override
    public void update(Role role) {
        super.update(role);

        permissionMapper.deleteMiddle(role.getId());

        menuMapper.deleteMiddle(role.getId());
        //添加菜单权限
        permissionMapper.addMiddle(role.getId(),role.getPermissions());
        // 添加 按钮
        menuMapper.addMiddle(role.getId(),role.getMenus());

    }

    @Override
    public PageList<Role> queryByPage(BaseQuery query) {
        PageList<Role> rolePageList = super.queryByPage(query);
        List<Role> rows = rolePageList.getRows();
        List<Long> collect = rows.stream().map(e -> e.getId()).collect(Collectors.toList());
        rows.forEach(e->{
            Long id = e.getId();
            List<Long> p =  permissionMapper.findByIdMiddle(id);
            e.setPermissions(p);
           List<Menu> menus = menuMapper.findByIdMiddle(id);
            e.setOwnMenus(menus);
        });
        return rolePageList;
    }
}